package com.scores.controller;
import com.scores.pojo.Subject;
import com.scores.service.SubjectService;
import com.scores.utils.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/subject")
public class SubjectController {
    @Autowired
    SubjectService subjectService;

    @RequestMapping("/getAllSubject")
    public Results<List<Subject>> getAllSubjectByPage(Subject subject, Integer page, Integer limit) {
        List<Subject> subjectList;
        if(page==null||limit==null){
            subjectList= subjectService.getAllSubjectByPage(subject, null, null);
        }else{
            subjectList = subjectService.getAllSubjectByPage(subject, (page-1)*limit, limit);
        }
        int count = subjectService.getAllSubjectCount(subject);
        return new Results<>("0", "success", subjectList, count);
    }

    @RequestMapping("/addSubject")
    public Results<String> addSubject(Subject subject) {
        int resultCode = subjectService.addSubject(subject);
        if (resultCode == 0) {
            return new Results<>("0", "添加成功", null, 0);
        } else {
            return new Results<>("2", "添加失败", null, 0);
        }
    }

    @RequestMapping("/updateSubject")
    public Results<String> updateSubject(Subject subject) {
        int resultCode = subjectService.updateSubject(subject);
        if (resultCode == 0) {
            return new Results<>("0", "更新成功", null, 0);
        } else {
            return new Results<>("1", "更新失败", null, 0);
        }
    }

    @RequestMapping("/deleteSubject")
    public Results<String> deleteSubject(Subject subject) {
        int count = subjectService.deleteSubject(subject);
        if (count == 0) {
            return new Results<>("0", "删除成功", null, 0);
        }else if(count == 2){
            return new Results<>("2", "该学科还有成绩数据，不能删除", null, 0);
        } else {
            return new Results<>("1", "删除失败", null, 0);
        }
    }
}
